# Add password hashing! (Later)
class User < ActiveRecord::Base

	has_many :posts, :dependent => :destroy
  has_many :votes
  belongs_to :user_level

	validates_presence_of :name
	validates_uniqueness_of :name
	validates_presence_of :password
	validates_presence_of :email
  validates_uniqueness_of :email

	def validate
		errors.add("name", "Symbols not allowed in names.") if self.name =~ /[<> +=!@\\\/?\#$%^&*.,\{\}\[\]\(\)~`"':;|]+/m
    errors.add("password", "Symbols not allowed in names.") if self.name =~ /[<> +=!@\\\/?\#$%^&*.,\{\}\[\]\(\)~`"':;|]+/m
		errors.add("name", "HTML not allowed in names.") if self.name =~ /(<.+>.+<\/.+>)|(<.+\/>)/m
		errors.add("email", "Not a valid e-mail address.") if !(self.email =~ RFC822)
    errors.add("signature", "Chevrons not allowed in signatures.") if self.signature =~ /[<>]/
	end

	def self.is_admin(user_id)
		user = User.find_by_id(user_id)
		if !user.nil?
			return user.user_level == UserLevel.find_by_name("Admin")
		else
			return false
		end
	end

  def self.is_mod(user_id)
		user = User.find_by_id(user_id)
		if !user.nil?
			return user.user_level == UserLevel.find_by_name("Mod")
		else
			return false
		end
	end

  def self.get_user_level_id( id )
    u = User.find_by_id(id)
    if u.nil?
      return UserLevel.find_by_name("Public").id.to_i
    end
    return (u.user_level_id).to_i
  end

	def toggle_admin_status
    #return ( self.is_admin = ((self.is_admin) ^ true ) )
    if( self.user_level == UserLevel.find_by_name("Admin") )
      self.user_level = UserLevel.find_by_id(2)
    else
      self.user_level = UserLevel.find_by_name("Admin")
    end
    self.save
	end

  def set_user_level( ul )
    self.user_level = UserLevel.find_by_id(ul)
  end

  def voted?( post_id )
    return !(Vote.find_by_post_id_and_user_id( post_id, self.id ).nil?)
  end

  def voted_positive?(post_id)
    vote = Vote.find_by_post_id_and_user_id( post_id, self.id )
    return vote.value == 1
  end


end
